<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="景区名称" prop="scenicName">
        <el-input v-model="queryParams.scenicName" placeholder="请输入景区名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="门店名称" prop="storeName">
        <el-input v-model="queryParams.storeName" placeholder="请输入门店名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="门店地址" prop="storeAdress">
        <el-input v-model="queryParams.storeAdress" placeholder="请输入门店地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="storePhone">
        <el-input v-model="queryParams.storePhone" placeholder="请输入联系电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="店长姓名" prop="managerName">
        <el-input v-model="queryParams.managerName" placeholder="请输入店长姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="成立时间" prop="establishmentsTime">
        <el-date-picker clearable v-model="queryParams.establishmentsTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择成立时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:storelist:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:storelist:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:storelist:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:storelist:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 门店列表表格 -->
    <el-table v-loading="loading" :data="storelistList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="门店ID" align="center" prop="storeId" />
      <el-table-column label="景区名称" align="center" prop="scenicName" />
      <el-table-column label="门店名称" align="center" prop="storeName" />
      <el-table-column label="门店地址" align="center" prop="storeAdress" />
      <el-table-column label="联系电话" align="center" prop="storePhone" />
      <el-table-column label="经度" align="center" prop="longitude" />
      <el-table-column label="纬度" align="center" prop="latitude" />
      <el-table-column label="店长姓名" align="center" prop="managerName" />
      <el-table-column label="关联商品信息" align="center">
        <template slot-scope="scope">
          <!-- 超链接：点击打开对话框 -->
          <el-link type="primary" @click="openDialog(scope.row)">
            查看商品信息
          </el-link>

          <!-- 对话框：展示底图表格 -->
          <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" append-to-body>
            <el-table :data="currentStore.producList" style="width: 100%">
              <!-- 底图图片列（Base64 渲染） -->
              <el-table-column label="商品封面图" align="center" prop="productImage" width="100">
                <template slot-scope="scope">
                  <image-preview :src="scope.row.productImage" :width="50" :height="50" />
                </template>
              </el-table-column>
              <!-- 其他底图信息列 -->
              <el-table-column label="商品名称" align="center" prop="productName" width="150" />
              <el-table-column label="商品介绍" align="center" prop="productIntroduce" width="300" />
              <el-table-column label="商品尺寸类型" align="center">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.img_product_type" :value="scope.row.productSizeType" />
                </template>
              </el-table-column>
            </el-table>
          </el-dialog>
        </template>
      </el-table-column>
      <el-table-column label="成立时间" align="center" prop="establishmentsTime" width="180">
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.establishmentsTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联商品" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAddProduct(scope.row)">关联商品</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:storelist:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:storelist:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 新增底图对话框 -->
    <el-dialog :title="`关联商品 - ${currentStore.storeName}`" :visible.sync="productDialogVisible" width="1400px"
      append-to-body>
      <el-table :data="currentStoreProductList" style="width: 100%">
        <!-- 底图图片列 -->
        <el-table-column label="商品封面图" align="center" prop="productImage" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.productImage" :width="50" :height="50" />
          </template>
        </el-table-column>
        <!-- 其他底图信息列 -->
        <el-table-column label="商品名称" align="center" prop="productName" width="150" />
        <el-table-column label="商品介绍" align="center" prop="productIntroduce" width="300" />
        <el-table-column label="商品类型" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.img_product_type" :value="scope.row.productSizeType" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- 新增点击事件，传递 storeId 和 productId -->
            <el-button size="mini" type="text" icon="el-icon-plus"
              @click="handleAddProductItem(scope.row)">添加</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加或修改门店信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="景区名称" prop="scenicName">
          <el-input v-model="form.scenicName" placeholder="请输入景区名称" />
        </el-form-item>
        <el-form-item label="门店名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="门店地址" prop="storeAdress">
          <el-input v-model="form.storeAdress" placeholder="请输入门店地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="storePhone">
          <el-input v-model="form.storePhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="店长姓名" prop="managerName">
          <el-input v-model="form.managerName" placeholder="请输入店长姓名" />
        </el-form-item>
        <el-form-item label="成立时间" prop="establishmentsTime">
          <el-date-picker clearable v-model="form.establishmentsTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择成立时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStorelist,
  getStorelist,
  delStorelist,
  addStorelist,
  updateStorelist,
  addStoreProduct
} from "@/api/system/storelist";

import {
  listProductlist,
} from "@/api/system/productlist";

export default {
  name: "Storelist",
  dicts: ['img_product_type'],
  data() {
    return {
      dialogVisible: false,
      dialogTitle: "",
      currentStore: {},
      productDialogVisible: false,
      currentStoreProductList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店信息表格数据
      storelistList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      productList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scenicName: null,
        storeName: null,
        storeAdress: null,
        storePhone: null,
        managerName: null,
        longitude: null,
        latitude: null,
        establishmentsTime: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scenicName: [
          { required: true, message: "景区名称不能为空", trigger: "blur" },
        ],
        storeName: [
          { required: true, message: "门店名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    openDialog(store) {
      this.currentStore = store;
      this.dialogTitle = `商品详情 - ${store.storeName}`;
      this.dialogVisible = true;
    },
    /** 查询底图表列表 */
    getProductList(storeId) {
      this.loading = true;
      listProductlist({ storeId }).then((response) => {
        this.currentStoreProductList = response.rows;
        this.loading = false;
      });
    },
    /** 查询门店信息列表 */
    getList() {
      this.loading = true;
      listStorelist(this.queryParams).then((response) => {
        this.storelistList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeId: null,
        scenicName: null,
        storeName: null,
        storeAdress: null,
        storePhone: null,
        managerName: null,
        establishmentsTime: null,
        createTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.storeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加门店信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const storeId = row.storeId || this.ids;
      getStorelist(storeId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改门店信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.storeId != null) {
            updateStorelist(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStorelist(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const storeIds = row.storeId || this.ids;
      this.$modal
        .confirm('是否确认删除门店信息编号为"' + storeIds + '"的数据项？')
        .then(() => delStorelist(storeIds))
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/storelist/export",
        {
          ...this.queryParams,
        },
        `storelist_${new Date().getTime()}.xlsx`
      );
    },
    handleAddProduct(store) {
      this.currentStore = store;
      this.productDialogVisible = true;
      this.getProductList(store.storeId);
    },
    handleAddProductItem(row) {
      const storeId = this.currentStore.storeId; // 门店 ID
      const productId = row.productId; // 底图 ID
      const productName = row.productName; // 底图 名称


      this.$modal
        .confirm('是否确认关联商品名称为"' + productName + '"的数据项？')
        .then(() => addStoreProduct(storeId, productId))
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("关联成功");
          this.productDialogVisible = false;
        })
    }

  },
};
</script>